<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-box">
        <input 
          class="search-input" 
          placeholder="搜索商品" 
          v-model="searchKeyword"
          @confirm="onSearch"
        />
        <view class="search-icon" @click="onSearch">🔍</view>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view 
        class="filter-item" 
        :class="{ active: currentCategory === '' }"
        @click="selectCategory('')"
      >
        全部
      </view>
      <view 
        class="filter-item" 
        :class="{ active: currentCategory === category }"
        v-for="category in categories" 
        :key="category"
        @click="selectCategory(category)"
      >
        {{ category }}
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-list">
      <view 
        class="product-item" 
        v-for="product in products" 
        :key="product.id"
        @click="goToDetail(product.id)"
      >
        <image 
          :src="getProductImage(product)" 
          class="product-image" 
          mode="aspectFill"
        />
        <view class="product-info">
          <text class="product-title">{{ product.title }}</text>
          <text class="product-desc">{{ product.description }}</text>
          <view class="product-meta">
            <text class="product-price">¥{{ product.price }}</text>
            <text class="product-location">{{ product.location }}</text>
          </view>
          <view class="product-footer">
            <view class="user-info">
              <image 
                :src="getUserAvatar(product.userId || product.id)" 
                class="user-avatar"
              />
              <text class="user-name">{{ product.userName || '匿名用户' }}</text>
            </view>
            <text class="product-time">{{ formatTime(product.createdAt) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore">
      <text v-if="loading">加载中...</text>
      <text v-else @click="loadMore">点击加载更多</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && products.length === 0">
      <text class="empty-text">暂无商品</text>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request.js';
import { API_BASE_URL } from '@/utils/config.js';

export default {
  data() {
    return {
      products: [],
      categories: ['数码产品', '服装配饰', '图书音像', '家居用品', '运动户外', '其他'],
      currentCategory: '',
      searchKeyword: '',
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      loading: false
    };
  },
  onLoad(options) {
    // 从参数中获取分类
    if (options.category) {
      this.currentCategory = options.category;
    }
    this.loadProducts();
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
    }
  },
  onPullDownRefresh() {
    this.currentPage = 1;
    this.products = [];
    this.hasMore = true;
    this.loadProducts().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    async loadProducts() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        if (this.currentCategory) {
          params.category = this.currentCategory;
        }
        
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword;
        }
        
        const response = await request({
          url: '/api/product/list',
          method: 'GET',
          data: params
        });
        
        console.log('商品列表API响应:', response);
         
         let newProducts = [];
         
         // 解析API响应格式 {code: 200, message: "...", data: {products: [...], pagination: {...}}}
         if (response && response.code === 200 && response.data && response.data.products) {
           newProducts = response.data.products;
         } else if (response && response.success && response.data && response.data.products) {
           // 兼容旧格式
           newProducts = response.data.products;
         } else if (response && response.data && Array.isArray(response.data)) {
           newProducts = response.data;
         } else if (response && Array.isArray(response)) {
           newProducts = response;
         } else if (response && (response.code === 200 || response.success)) {
           // 如果API返回成功但没有找到products数组
           console.log('API返回成功但未找到商品数据:', response);
           uni.showToast({
             title: '暂无商品数据',
             icon: 'none'
           });
         } else {
           console.log('API调用失败:', response);
           uni.showToast({
             title: response?.message || '加载失败',
             icon: 'none'
           });
         }
        
        console.log('解析到的商品数据:', newProducts);
        
        if (this.currentPage === 1) {
          this.products = newProducts;
        } else {
          this.products = [...this.products, ...newProducts];
        }
        
        this.hasMore = newProducts.length === this.pageSize;
      } catch (error) {
        console.error('加载商品失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    loadMore() {
      this.currentPage++;
      this.loadProducts();
    },
    
    selectCategory(category) {
      this.currentCategory = category;
      this.currentPage = 1;
      this.products = [];
      this.hasMore = true;
      this.loadProducts();
    },
    
    onSearch() {
      this.currentPage = 1;
      this.products = [];
      this.hasMore = true;
      this.loadProducts();
    },
    
    goToDetail(productId) {
      uni.navigateTo({
        url: `/pages/productDetail/index?id=${productId}`
      });
    },
    
    getProductImage(product) {
      // 优先使用API返回的firstImageUrl字段
      if (product.firstImageUrl) {
        const img = product.firstImageUrl;
        if (img.startsWith('http')) {
          return img;
        }
        if (img.startsWith('/uploads/')) {
          return API_BASE_URL + img;
        }
        return img;
      }
      // 兼容imageUrls数组格式
      if (product.imageUrls && product.imageUrls.length > 0) {
        const img = product.imageUrls[0];
        if (img.startsWith('http')) {
          return img;
        }
        if (img.startsWith('/uploads/')) {
          return API_BASE_URL + img;
        }
        return img;
      }
      return 'https://picsum.photos/300/200?random=' + product.id;
    },
    
    getUserAvatar(userId) {
      return `https://picsum.photos/40/40?random=${userId}`;
    },
    
    formatTime(timeStr) {
      if (!timeStr) return '';
      
      const time = new Date(timeStr);
      const now = new Date();
      const diff = now - time;
      
      const minutes = Math.floor(diff / (1000 * 60));
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (minutes < 60) {
        return `${minutes}分钟前`;
      } else if (hours < 24) {
        return `${hours}小时前`;
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return time.toLocaleDateString();
      }
    }
  }
};
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  background: #fff;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 8px 40px 8px 12px;
  border-radius: 20px;
  background: #f5f5f5;
  border: none;
  font-size: 14px;
}

.search-icon {
  position: absolute;
  right: 12px;
  font-size: 16px;
  color: #666;
}

.filter-bar {
  background: #fff;
  padding: 12px 16px;
  display: flex;
  gap: 16px;
  border-bottom: 1px solid #eee;
  overflow-x: auto;
  white-space: nowrap;
}

.filter-item {
  padding: 6px 12px;
  border-radius: 16px;
  background: #f5f5f5;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
}

.filter-item.active {
  background: #FF5E5E;
  color: #fff;
}

.product-list {
  padding: 12px;
}

.product-item {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
  display: flex;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.product-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  flex-shrink: 0;
}

.product-info {
  flex: 1;
  padding: 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: #FF5E5E;
}

.product-location {
  font-size: 12px;
  color: #999;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 6px;
}

.user-name {
  font-size: 12px;
  color: #666;
}

.product-time {
  font-size: 12px;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-text {
  color: #999;
  font-size: 16px;
}
</style>